package org.kobu;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class WCopy {

    private final File from;
    private final File to;

    public WCopy(final File from, final File to) {
        this.from = from;
        this.to = to;
    }

    public void copy() throws IOException {
        final FilesIterator iterator = new FilesIterator(from);
        while (iterator.hasNext()) {
            final FileData source = iterator.next();
            final File target = new File(to, source.getRelativePath());
            if (source.isDirectory()) {
                if (target.isDirectory()) {
                    System.out.println("Folder \"" + target + "\" already exists.");
                } else {
                    System.out.println("Create \"" + target + "\".");
                    if (!target.mkdirs()) {
                        System.err.println("Failed to create \"" + target + "\".");
                    }
                }
            } else {
                copyFile(source.getFile(), target);
            }
        }
    }

    private static void copyFile(final File source, final File target) throws IOException {
        System.out.println("Copy \"" + source + "\" to \"" + target + "\".");
        final Path fromPath = FileSystems.getDefault().getPath(source.getAbsolutePath());
        final Path toPath = FileSystems.getDefault().getPath(target.getAbsolutePath());
        Files.copy(fromPath, toPath, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
    }

    public static void main(String[] args) throws IOException {
        if (args.length == 2) {
            final long start = System.currentTimeMillis();
            new WCopy(new File(args[0]), new File(args[1])).copy();
            System.out.println("Time: " + (System.currentTimeMillis() - start) + " ms.");
        }
    }
}